package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServicelmpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //固定访问路径
    private static String https="https://api.weixin.qq.com/sns/jscode2session";


    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        //1.设置请求参数
        String result = getString(code);
        //解析请求数据 是一个json的字符串 openid 是判断用户的唯一标识
        //code是请求的参数 每次code只能使用一次
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        //如果openid 是null 则登录失败
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //如果登录成功 判断是不是第一次登录如果是则保存
       User user  =userMapper.SelectByopenId(openid);
        if (user==null){
            User user1 = new User();
            user1.setOpenid(openid);
            user1.setCreateTime(LocalDateTime.now());
            userMapper.Insert(user1);
            return user1;
        }
        return user;
    }

    private String getString(String code) {
        Map<String,String> map=new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("grant_type","authorization_code");
        map.put("js_code", code);
        //发送请求
        String result    = HttpClientUtil.doGet(https,map);
        return result;
    }
}
